package com.douhao.personal.controller;

import com.douhao.personal.core.shiro.token.manager.TokenManager;
import com.douhao.personal.model.RoleUserBo;
import com.douhao.personal.model.User;
import com.douhao.personal.model.UserRoleBo;
import com.douhao.personal.service.UserService;
import com.douhao.personal.util.Page;
import com.douhao.personal.util.UserManager;
import org.apache.shiro.authc.AccountException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Resource
    private UserService userService;

    /**
     * 登录跳转
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView login() {
        return new ModelAndView("login");
    }

    /**
     * @param user       登录的user
     * @param rememberMe 是否技术
     * @param request    request用来获取登录之前的url，用来登陆后跳转到登录之前的页面
     */
    @RequestMapping(value = "/submitLogin", method = RequestMethod.POST)
    public Map<String, Object> login(User user, boolean rememberMe, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            TokenManager.login(user, rememberMe);
            User currentUser = TokenManager.getToken();
            request.getSession().setAttribute("currentUser", currentUser);
            resultMap.put("status", 200);
            resultMap.put("massage", "登录成功");
        } catch (AccountException e) {
            resultMap.put("status", 500);
            resultMap.put("message", "帐号或密码不正确");
        } catch (Exception e) {
            resultMap.put("status", 500);
            resultMap.put("message", "服务器错误");
        }
        return resultMap;
    }

    /**
     * 用户列表
     */
    @RequestMapping(value = "/userList")
    public ModelAndView userList(String pageNo, User user) {
        Page<User> userList = userService.pageList(user, pageNo == null ? 1 : Integer.valueOf(pageNo), pageSize);
        ModelAndView modelAndView = new ModelAndView("permit/userList", "page", userList);
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    /**
     * 用户删除
     */
    @RequestMapping(value = "deleteUserById", method = RequestMethod.POST)
    public Map<String, Object> deleteUserById(String ids) {
        return userService.deleteUserById(ids);
    }

    /**
     * 用户分配角色
     */
    @RequestMapping(value = "/userBoList")
    public ModelAndView userBoList(String pageNo, UserRoleBo userRoleBo) {
        Page<UserRoleBo> userList = userService.findUserAndRole(userRoleBo, pageNo == null ? 1 : Integer.valueOf(pageNo), pageSize);
        ModelAndView modelAndView = new ModelAndView("permit/userRoleBoList", "page", userList);
        modelAndView.addObject("userRoleBo", userRoleBo);
        return modelAndView;
    }

    /**
     * 查询用户拥有的角色
     */
    @RequestMapping(value = "/selectRoleByUserId")
    public List<RoleUserBo> selectRoleByUserId(String id) {
        List<RoleUserBo> bos = userService.selectRoleByUserId(id);
        return bos;
    }

    /**
     * 保存勾选的角色
     */
    @RequestMapping(value = "addRole2User")
    public Map<String, Object> addRole2User(String userId, String ids) {
        return userService.addRole2User(userId, ids);
    }


    /**
     * 根据用户id清空角色。
     *
     * @param userIds 用户ID ，以‘,’间隔
     */
    @RequestMapping(value = "clearRoleByUserIds")
    public Map<String, Object> clearRoleByUserIds(String userIds) {
        return userService.deleteRoleByUserIds(userIds);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public Map<String, Object> logOut(String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            TokenManager.logout();
            resultMap.put("status", 200);
            resultMap.put("message", "退出成功");
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("status", 500);
            logger.error("errorMessage:" + e.getMessage());
        }
        return resultMap;
    }


    /**
     * 个人资料
     *
     * @return
     */
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public ModelAndView userIndex() {
        return new ModelAndView("user/info");
    }

    /**
     * 跳转到修改个人资料页面
     */
    @RequestMapping(value = "jumpUpdateSelf", method = RequestMethod.GET)
    public ModelAndView jumpUpdateSelf() {
        return new ModelAndView("user/updateSelf");
    }

    /**
     * 跳转到修改密码页面
     */
    @RequestMapping(value = "jumpUpdatePswd", method = RequestMethod.GET)
    public ModelAndView jumpUpdatePswd() {
        return new ModelAndView("user/updatePswd");
    }

    /**
     * 密码修改
     *
     * @return
     */
    @RequestMapping(value = "updatePswd", method = RequestMethod.POST)
    public Map<String, Object> updatePswd(String pswd, String newPswd) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        //根据当前登录的用户帐号 + 老密码，查询。
        String email = TokenManager.getToken().getEmail();
        pswd = UserManager.md5Pswd(email, pswd);
        User user = userService.login(email, pswd);

        if ("admin".equals(email)) {
            resultMap.put("status", 300);
            resultMap.put("message", "管理员不准修改密码。");
            return resultMap;
        }

        if (null == user) {
            resultMap.put("status", 300);
            resultMap.put("message", "密码不正确！");
        } else {
            user.setPswd(newPswd);
            //加工密码
            user = UserManager.md5Pswd(user);
            //修改密码
            userService.updateByPrimaryKeySelective(user);
            resultMap.put("status", 200);
            resultMap.put("message", "修改成功!");
            //重新登录一次
            TokenManager.login(user, Boolean.TRUE);
        }
        return resultMap;
    }

    /**
     * 个人资料修改
     *
     * @return
     */
    @RequestMapping(value = "updateSelf", method = RequestMethod.POST)
    public Map<String, Object> updateSelf(User entity) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            userService.updateByPrimaryKeySelective(entity);
            resultMap.put("status", 200);
            resultMap.put("message", "修改成功!");
        } catch (Exception e) {
            resultMap.put("status", 500);
            resultMap.put("message", "修改失败!");
        }
        return resultMap;
    }

}
